
#include "Graph.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <vector>
#include "Worker.h"
#include "string.h"
#include "stdlib.h"

using namespace std;

Graph::Graph() {
	_number_of_nodes	= 0;
	_buffer_size		= 0;
	_nodes				= new vector<Worker*>();
	//build_graph(filename);
}

Graph::~Graph() {
    vector<Worker*>::iterator iter = _nodes->begin();
    int i=0;
    while( iter != _nodes->end() )
    {
        delete(_nodes->at(i));
        iter = _nodes->erase( iter );
        ++iter;
        i++;
    }
	delete(_nodes);
}

bool Graph::build_graph(string filename, Mailbox* mailer_mailbox)
{
	// parsing input file:
	FILE* input_file;
	input_file = fopen(filename.c_str(), "r");
	if ( input_file == NULL )
	{
		cout << "Couldn't open input file " << filename << "." << endl;
		return false;
	}
	else
	{
		cout << "File " << filename << " opened." << endl;
		char line[100];

		// Mailer buffer size:
		fgets(line, 10, input_file);
		std::stringstream ss1(line);
		ss1 >> _buffer_size;

		// number of nodes:
		fgets(line, 10, input_file);
		std::stringstream ss2(line);
		ss2 >> _number_of_nodes;

		// neighbors:
		while ( !_nodes->empty() )
		{
			_nodes->pop_back();
		}

		_nodes->push_back(NULL);
		while ( fgets(line, 100, input_file) != NULL )
		{
		    int serial_number;
		    stringstream ss3(line);
		    ss3 >> serial_number;
		    Worker *worker = new Worker(serial_number, _number_of_nodes/*, mailer_mailbox*/);
		    int neighbour, last_neighbour = -1;
		    while (true)
		    {
		    	ss3 >> neighbour;
		    	if ( neighbour == last_neighbour )
		    		break;
		    	worker->set_neighbour(neighbour);
		    	last_neighbour = neighbour;
		    }
		    _nodes->push_back(worker);
		}

		fclose(input_file);
		//cout << "Buffer size:     " << _buffer_size << endl;
		//cout << "Number of nodes: " << _number_of_nodes << endl;
		//cout << "Parsing ended." << endl;
		return true;
	}
}

int Graph::get_buffer_size()
{
	return _buffer_size;
}
void Graph::print()
{
	for (unsigned int i = 0; i < _nodes->size(); ++i) {
		((Worker*)_nodes->at(i))->print();
	}
}
